package JFrame;

import Class.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.time.*;
import java.time.temporal.ChronoUnit;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.Date;

// 取款界面
public class WithdrawalJFrame extends JFrame implements ActionListener {
    JLabel labelMoney = new JLabel("取出钱数");
    JTextField tfdMoney = new JTextField(12);
    JButton btnConfirm = new JButton("确定");
    JButton btnClear = new JButton("清空");

    public WithdrawalJFrame() {
        this.setName("村镇银行业务储蓄系统");
        this.setTitle("取款界面");
        this.setSize(300, 200);
        this.setAlwaysOnTop(true);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(2);
        this.setLayout(new FlowLayout());
        this.setVisible(true);

        JPanel p1 = new JPanel();
        p1.add(labelMoney);
        p1.add(tfdMoney);
        JPanel p2 = new JPanel();
        p2.add(btnConfirm);
        p2.add(btnClear);
        this.add(p1);
        this.add(p2);
        btnConfirm.addActionListener(this);
        btnClear.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == btnConfirm) {
            try {
                if(queryDemandMoney()){
                    WithdrawalSuccessJFrame withdrawalSuccessJFrame = new WithdrawalSuccessJFrame();
                    return;
                }
                if(queryTimeMoney()){
                    WithdrawalSuccessJFrame withdrawalSuccessJFrame = new WithdrawalSuccessJFrame();
                    return;
                }
                WithdrawalFailedJFrame failedJFrame = new WithdrawalFailedJFrame();
            } catch (Exception exception) {
                System.out.println("取款出现异常");
            }
        }
        if (e.getSource() == btnClear) {
            tfdMoney.setText("");
        }
    }

    public boolean queryDemandMoney() throws Exception {
        User user = LoginJFrame.getUser();
        ResultSet result = null;
        Connection connection = null;
        double queryMoney = -1;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String ur1 = "jdbc:mysql://localhost:3306/bank";
            String username = "root";               //数据库用户名
            String mypassword = "20222746";          //数据库密码
            connection = DriverManager.getConnection(ur1, username, mypassword);
            PreparedStatement pst = null;
            ResultSet resultSet = null;
            String cno = user.getCardNumber();
            double needMoney = Double.parseDouble(tfdMoney.getText());
            String sql = "select * from demanddeposit where card = ? and money >= ?";
            pst = connection.prepareStatement(sql);
            pst.setString(1, cno);
            pst.setDouble(2, needMoney);
            resultSet = pst.executeQuery();
            double demandInterest = 0;
            while (resultSet.next()) {
                // 找到符合要求的一条活期存款记录
                queryMoney = resultSet.getDouble("money");
//                System.out.println(queryMoney);
                java.sql.Date depositDate = resultSet.getDate("depositDate");
                java.util.Date date = new java.util.Date(depositDate.getTime());
//                System.out.println(date);
                LocalDate formerDate = convertToLocalDate(date);
//                System.out.println(formerDate);
                LocalDate nowDate = LocalDate.now();
                // 计算此次活期存款存了多少天
                long deltaDays = ChronoUnit.DAYS.between(formerDate, nowDate);
                DemandRate rate = new DemandRate();
                // 计算活期利息
                demandInterest = rate.getDemandInterest(queryMoney, deltaDays);
            }
            // 没有一条存款记录能够取出钱
            if(queryMoney == -1)
                return false;
            // 插入取款记录
            sql = "insert into withdrawal values(?, ?, ?, ?, ?)";
            pst = connection.prepareStatement(sql);
            pst.setString(1, user.getCardNumber());
            pst.setString(2,"活期取款");
            pst.setDouble(3, needMoney);
            pst.setDouble(4, demandInterest);
            java.util.Date utilDate = new Date();
            java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
            pst.setDate(5, sqlDate);
            pst.executeUpdate();

            // 更新用户的活期余额
            double m = LoginJFrame.user.getDemandMoney();
            sql = "update user set demandMoney = ? where cardNumber = ?";
            pst = connection.prepareStatement(sql);
            pst.setDouble(1, m + demandInterest - needMoney);
            pst.setString(2, cno);
            pst.executeUpdate();
            connection.close();
            pst.close();
            return true;
        }catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public boolean queryTimeMoney() throws Exception {
        User user = LoginJFrame.getUser();
        ResultSet result = null;
        Connection connection = null;
        double queryMoney = -1;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String ur1 = "jdbc:mysql://localhost:3306/bank";
            String username = "root";               //数据库用户名
            String mypassword = "20222746";          //数据库密码
            connection = DriverManager.getConnection(ur1, username, mypassword);
            PreparedStatement pst = null;
            ResultSet resultSet = null;
            String cno = user.getCardNumber();
            double needMoney = Double.parseDouble(tfdMoney.getText());
            String sql = "select * from timedeposit where card = ? and money >= ?";
            pst = connection.prepareStatement(sql);
            pst.setString(1, cno);
            pst.setDouble(2, needMoney);
            resultSet = pst.executeQuery();
            double timeInterest = 0;
            while (resultSet.next()) {
                // 找到符合要求的一条定期存款记录
                queryMoney = resultSet.getDouble("money");
//                System.out.println(queryMoney);
                java.sql.Date depositDate = resultSet.getDate("depositDate");
                java.util.Date date = new java.util.Date(depositDate.getTime());
//                System.out.println(date);
                LocalDate formerDate = convertToLocalDate(date);
//                System.out.println(formerDate);
                LocalDate nowDate = LocalDate.now();
                // 计算此次定期存款存了多少月
                long deltaMonths = ChronoUnit.MONTHS.between(formerDate, nowDate);
                // 计算此次定期存款存了多少天
                long deltaDays = ChronoUnit.DAYS.between(formerDate, nowDate);
                TimeRate timeRate = new TimeRate();
                timeInterest = timeRate.getTimeInterest(queryMoney, deltaMonths, deltaDays);
            }
            // 没有一条存款记录能够取出钱
            if(queryMoney == -1)
                return false;
            // 插入取款记录
            sql = "insert into withdrawal values(?, ?, ?, ?, ?)";
            pst = connection.prepareStatement(sql);
            pst.setString(1, LoginJFrame.getUser().getCardNumber());
            pst.setString(2,"定期取款");
            pst.setDouble(3, needMoney);
            pst.setDouble(4, timeInterest);
            java.util.Date utilDate = new Date();
            java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
            pst.setDate(5, sqlDate);
            pst.executeUpdate();

            // 更新用户的活期余额
            double m = LoginJFrame.user.getDemandMoney();
            sql = "update user set timeMoney = ? where cardNumber = ?";
            pst = connection.prepareStatement(sql);
            pst.setDouble(1, m + timeInterest - needMoney);
            pst.setString(2, cno);
            pst.executeUpdate();
            connection.close();
            pst.close();
            return true;
        }catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
    public LocalDate convertToLocalDate(java.util.Date dateToConvert) {
        return dateToConvert.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
    }

}
